package com.us.usws.support.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.iwsh.core.common.GlobalConfig;
import net.iwsh.core.common.Wildcard;
import net.iwsh.core.exception.GenericRuntimeException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.us.usws.biz.LoginOutWorker;
import com.us.usws.common.SiteConstants;
import com.us.usws.model.flat.system.DOUser;
import com.us.usws.service.ro.UserROService;
import com.us.usws.support.uitls.ServiceFactory;
import com.us.usws.support.uitls.SiteWebContext;

/**
 * ep server filter
 * @author Wang Jianbo
 */
public class IpodiumLoginFilter implements Filter {

	private static Log log = LogFactory.getLog(IpodiumLoginFilter.class);

	private String ignoreExp = "";

	/**
	 * The filter configuration object we are associated with. If this value is
	 * null, this filter instance is not currently configured.
	 */
	protected FilterConfig filterConfig = null;

	/**
	 * Take this filter out of service.
	 */
	public void destroy() {
		this.filterConfig = null;
	}

	/**
	 * Select and set (if specified) the character encoding to be used to
	 * interpret request parameters for this request.
	 *
	 * @param request  The servlet request we are processing
	 * @param response The servlet response we are creating
	 * @param chain	The filter chain we are processing
	 * @throws IOException	  if an input/output error occurs
	 * @throws ServletException if a servlet error occurs
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		//check whether the url should be ignored.
		String path = req.getRequestURI();
		log.info("path=[" + path + "].");

		if (shouldIgnore(path)) {
			log.debug("{IpodiumLoginFilter} :: Ignore URL: [" + path + "].");
			chain.doFilter(request, response);
			return;
		}

		//determine ep user in webcontext
		SiteWebContext wc = new SiteWebContext(req, resp);

		//if not logged-in yet
		if (!wc.isIpodiumLogin()) {
			//for debug purpose
			if (SiteConstants.IS_DEBUG) {
				fakeLogin(wc);
				chain.doFilter(request, response);
				return;
			} else {
				resp.sendRedirect("/ipodium/login.action");
				return;
			}
		}

		//do filter chain
		chain.doFilter(request, response);
	}

	/**
	 * Check whether str matches the regex
	 *
	 * @param str   servlet path to be checked
	 * @param regex regex to be ignored
	 * @return true if matches, false if not.
	 */
	private boolean shouldIgnore(String str) {
		if (ignoreExp == null) {
			return false;
		}
		return Wildcard.matchesIgnoreCase(ignoreExp, str, ",");
	}

	/**
	 * fake login
	 * @param wc
	 */
	public void fakeLogin(SiteWebContext wc) {
		String autoLoginName = GlobalConfig.getString("Commons/AutoLoginIpodiumLoginName");

		log.debug("Ipodium auto login with loginName=[" + autoLoginName + "].");
		UserROService service = ServiceFactory.getInstance().getService(UserROService.class);

		DOUser u = service.getDOUserByLoginName(autoLoginName);
		if (u == null) {
			throw new GenericRuntimeException("Cannot auto login. Add config first!");
		} else if (u.getRole() == null || u.getRole() != SiteConstants.CHANNEL_TARGET_ROLE_TEACHER) {
			throw new GenericRuntimeException("Non-teacher user of [" + autoLoginName + "]!");
		}

		//set to web context
		LoginOutWorker.ipodiumLogin(u, wc);
	}

	/**
	 * Place this filter into service.
	 *
	 * @param filterConfig The filter configuration object
	 */
	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
		this.ignoreExp = filterConfig.getInitParameter("ignoreExp");
	}

	/**
	 * Returns the filterConfig.
	 *
	 * @return FilterConfig
	 */
	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	/**
	 * Sets the filterConfig.
	 *
	 * @param filterConfig The filterConfig to set
	 */
	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

}
